import { queryCurrent, query, queryUsers, meInfo } from '@/services/user';
import { PARAMS_MAP } from "@/generic/ConfigParams";

const userInfoAdapter = (meInfo) => {  // 在此处相应修改，可适配所有的接口
  // 构建自定义的用户信息列表
  let userInfo = {};  // 符合我系统调用的 用户信息对象

  for (const key in meInfo) {
    const uKey = PARAMS_MAP[key]
    if (uKey) {
      userInfo[uKey] = meInfo[key];
    }
  }
  // console.log("===>> userInfo", userInfo)
  return userInfo;
}

const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    // userList: [],
  },
  effects: {

    *fetchUsers({ payload }, { call }) {
      let args = {}
      if (payload && payload.userid) {
        args = payload;
      }
      const response = yield call(queryUsers, args, true)
      // console.log("==>> fetchUsers", response, payload)
      if (!(response instanceof Response)) {
        if (response.results instanceof Array) {
          return response.results
        }
        return response;
      }
      return false;
    },

    *fetchCurrent(_, { call, put }) {
      const me = yield call(meInfo);
      // console.log("===>> me", me)
      yield put({
        type: 'saveCurrentUser',
        payload: userInfoAdapter(me),
      });
    },

  },
  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },

    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
